﻿package com.bluediesel.utils.managers.scenemanager.commands {
	import flash.events.Event;
	
	public class SerialCommand extends TimedCommand {
		
		private var _commands:Array = [];
		
		public function SerialCommand(delay:Number, ...commands) {
			for each (var cmd:Object in commands)
			{
				_commands.push(cmd);
				//trace ("Serial subcommand added: " + cmd);
			}
			super(delay);
		}
		
		override public function executeAll():void {
			execute();
		}
		
		private var _completeCommandCount:int;
		
		override final protected function execute(obj:Object = null):void {
			
			//set the complete command count to zero
			_completeCommandCount = 0;
			
			//listen for the complete event of the first subcommand...
			_commands[0].addEventListener(Event.COMPLETE, onSubcommandComplete);
			
			//...and start the subcommand
			//trace ("starting serial command " + (_completeCommandCount + 1).toString() + " " + _commands[0]);
			_commands[0].start();
		}
		
		private function onSubcommandComplete(e:Event):void {
			//trace ("serial subcommand complete: " + e.target);
			//stop listening for the complete event
			Command(e.target).removeEventListener(Event.COMPLETE, onSubcommandComplete);
			
			//increment the complete command count
			_completeCommandCount++;
			//trace ("serial command " + e.target + " is number " + _completeCommandCount + " of " + _commands.length );
			//if all the commands are complete...
			if (_completeCommandCount == _commands.length) {
				
				//...then this serial command is complete
				//trace ("serial command COMPLETE");
				complete();
			} else {
				
				//...otherwise listen for the complete event of the next subcommand...
				_commands[_completeCommandCount].addEventListener(Event.COMPLETE, onSubcommandComplete);

				//trace ("starting serial command " + (_completeCommandCount + 1).toString() + " " + e.target);
				//...and start the subcommand
				_commands[_completeCommandCount].start();
			}
		}
	}
}